<template>
  <a-modal v-model="mapModel" @cancel="destroy"
           width="80%" title="经纬度" centered :maskClosable="false" destroyOnClose>
    <div class="MapPop">
      <a-form-model layout="inline" :colon="false" :rules="rules" ref="ruleForm" :model="latlngform" class="mapfrom">
        <a-form-model-item label="经度" prop="x">
          <a-input v-model.number.trim="latlngform.x" placeholder="请输入经度" allow-clear/>
        </a-form-model-item>
        <a-form-model-item label="纬度" prop="y">
          <a-input v-model.number.trim="latlngform.y" placeholder="请输入纬度" allow-clear/>
        </a-form-model-item>
        <a-form-model-item label="公司名称">
          <a-auto-complete v-model="local" placeholder="请输入公司名称或者地名" @change="mapOnChange" @select="mapOnSelect"
                           allowClear>
            <template slot="dataSource">
              <a-select-option v-for="(v,i) in dataSource" :key="i.toString()" :value="JSON.stringify(v)">
                {{ v.name }}
              </a-select-option>
            </template>
          </a-auto-complete>
        </a-form-model-item>
        <a-form-model-item>
          <a-button @click="()=>{mouseTool.marker();}">
            <img src="@/assets/public/地图绘制1.png"/>
          </a-button>
        </a-form-model-item>
        <a-form-model-item>
          <a-button @click="()=>{map.remove(marker);latlngform.x ='';latlngform.y='';latlngform.geom=''}">
            <img src="@/assets/public/地图绘制4.png"/>
          </a-button>
        </a-form-model-item>
      </a-form-model>
      <div class="mapbox">
        <el-amap class="amapContainer" :amap-manager="amapManager" :events="events" :center="center" :zoom="zoom"
                 :vid="'amap-vue'"></el-amap>
      </div>
    </div>
    <template slot="footer">
      <a-button type="primary" @click="mapSubmit">确定</a-button>
    </template>
  </a-modal>
</template>

<script>
import {AMapManager, lazyAMapApiLoaderInstance} from "vue-amap";
let amapManager = new AMapManager();
export default {
  name: "index",
  props:{
    latlng:{required:true,type:Object}
  },
  data() {
    let thet = this;
    return {
      mapModel: false, // 经纬度弹窗
      latlngform: {
        x:"",
        y:"",
        geom:""
      },
      rules:{
        x:[{validator:this.isNunber,trigger: ['change','blur'] }],
        y:[{validator:this.isNunber,trigger: ['change','blur'] }]
      },
      // 地图
      amapManager,
      mapStyle: "amap://styles/39ba2088b6b8fc67184833f73cceab4d",
      zoom: 10,
      map: "",
      center: [118.4643, 32.0238],
      events: {
        init(o) {
          lazyAMapApiLoaderInstance.load().then(() => {
            thet.initPage();
          });
        },
      },
      mouseTool: "", // 鼠标点击实例
      marker: "", // 用户创建的点标记
      dataSource:[],  // 用户输入以后地图的自动填充
      local: "",  // 公司名称搜索
      fun:null,
    }
  },
  methods:{
    isNunber(rule, value, callback){
      if(value == ""){
        callback(new Error('经纬度坐标必填'));
      }else if(isNaN(value)){
        callback(new Error('请输入正确经纬度坐标'));
      }else {
        callback();
      }
    },
    //初始化地图
    initPage() {
      this.map = this.amapManager.getMap();
      this.map.plugin(["AMap.MouseTool"], () => {
        this.mouseTool = new AMap.MouseTool(this.map);
      });
      this.mouseTool.on("draw", (e) => {
        console.log("触发")
        if (this.marker) {
          this.map.remove(this.marker);
          this.marker = null;
        }
        this.latlngform.x = e.obj.getPosition().R;
        this.latlngform.y = e.obj.getPosition().Q;

        this.latlngform.geom = `POINT(${e.obj.getPosition().R} ${
            e.obj.getPosition().Q
        })`;
        this.marker = e.obj;
      });
    },
    // 用户输入
    mapOnChange(value){
      AMap.plugin('AMap.Autocomplete',()=>{
        // 实例化Autocomplete
        let autoOptions = {
          city: '全国'
        }
        let autoComplete = new AMap.Autocomplete(autoOptions);
        autoComplete.search(value, (status, result)=>{
          if(status == 'error'){
            this.dataSource = [];
            return
          }
          this.dataSource = result.tips
        })
      })
    },
    // 用户选中下拉
    mapOnSelect(value){
      let latlon = JSON.parse(value).location;
      if(!latlon){
        this.$message.info("选取的地点没有坐标");
        return
      }
      this.latlngform.y = latlon.lat;
      this.latlngform.x = latlon.lng;
      console.log(this.latlngform)
    },
    destroy() {
      this.latlngform = {};
      this.marker = null;
      this.mapModel = false;
    },
    // 地图确定按钮
    mapSubmit() {
      this.$refs.ruleForm.validate(valid => {
        console.log(valid)
        if (valid) {
          this.latlngform.geom = `POINT(${this.latlngform.x} ${this.latlngform.y})`;
          this.$emit("coordinateChang",this.latlngform);
          // this.form.geom = `POINT(${this.form.x} ${this.form.y})`;
          console.log("sss")
          this.destroy()
        }
      });

    },
    //  地图完
    debounce(fn, wait){
      if(this.fun !== null){
        clearTimeout(this.fun);
      }
      this.fun = setTimeout(fn, wait);
    },
    ff(){
      console.log(this.map,this.marker)
      if (this.marker) {
        this.marker.setPosition([this.latlngform.x, this.latlngform.y]);
      } else {
        this.marker = new AMap.Marker({
          position: new AMap.LngLat(this.latlngform.x, this.latlngform.y),
        });

        this.map.add(this.marker);
      }
      this.map.setCenter([this.latlngform.x, this.latlngform.y]);
      this.map.setFitView();
    },
    initData(){
      this.latlngform = JSON.parse(JSON.stringify(this.latlng));
      console.log(this.latlngform,this.latlng)
    },
  },
  mounted() {

  },
  watch:{
    latlngform: {
      deep: true,
      handler(newValue, oldValue) {
        if (newValue.x != "" && newValue.y != "") {
          if(!this.dataSource){
            this.local = "";
          }
          let x= Number(newValue.x),y = Number(newValue.y);
          if(isNaN(x)||isNaN(y)){
            return
          }
          this.debounce(this.ff,1000)

        } else {
          if (this.marker) {
            this.marker.setMap(null);
            this.marker = null;
          }
        }
      },
    },
  }
}
</script>

<style scoped lang="scss">
::v-deep .mapfrom.ant-form-inline .ant-form-item {
  margin-right: 16px;
  width: unset;
}
::v-deep .mapfrom.ant-form-inline .ant-form-item > .ant-form-item-control-wrapper {
  width: auto;
}
::v-deep.mapfrom.ant-form-inline .ant-form-item > .ant-form-item-label {
  width: auto;
}
// 地图
.MapPop {
  height: 500px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .mapbox {
      width: 100%;
      height: 90%;
  }
}
</style>